package {
	import com.Controller;
	import com.Data;
	import com.Lang;
	import com.View;
	import com.utils.URI;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	[SWF(width = "760", height = "590", backgroundColor = "#cccccc")]
	public class Game extends Sprite {

		public static var Instance:Game;

		private var _data:Data;
		private var _ctrl:Controller;
		private var _view:View;
		private var _lang:Lang;
		private var _timer:Timer;
		private var _target:Sprite;

		public function Game() {
			if (stage) {
				init(null);
			} else {
				this.addEventListener(Event.ADDED_TO_STAGE, init);
			}
		}

		private function init(event:Event = null):void {
			this.removeEventListener(Event.ADDED_TO_STAGE, init);
			Instance = this;
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			URI.analyze(this);

			this._data = new Data();
			this._ctrl = new Controller();
			this._view = new View(stage);
			this._lang = new Lang();
			this._data.onConnect = function():void {
				_view.show();
			}
			this._view.init(this._data, this._ctrl, this._lang);
			this._ctrl.init(this._data, this._lang);
			this._data.init(this._view, this._ctrl);

			this.settleAge();
		}

		private function settleAge():void {
			this._timer = new Timer(1000);
			this._timer.addEventListener(TimerEvent.TIMER, this.timerHandler);
			this._timer.start();
			this._target = new Sprite();
			this._target.addEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
		}

		public function unsettleAge():void {
			if (this._timer) {
				this._timer.removeEventListener(TimerEvent.TIMER, this.timerHandler);
				this._timer = null;
			}
			if (this._target) {
				this._target.removeEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
				this._target = null;
			}
		}

		private function timerHandler(_arg1:TimerEvent):void {
			this._data.timerProcess();
			this._ctrl.timerProcess();
			this._view.timerProcess();
		}

		private function enterFrameHandler(_arg1:Event):void {
			this._data.frameProcess();
			this._ctrl.frameProcess();
			this._view.frameProcess();
		}
	}
}
